import React, { useState, useEffect } from 'react'
import { 
  Layout, 
  Card, 
  Row, 
  Col, 
  Descriptions, 
  Tag, 
  Tabs, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input,
  message,
  Statistic,
  Space
} from 'antd'
import { 
  ArrowLeftOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  PlayCircleOutlined
} from '@ant-design/icons'
import { useParams, useNavigate } from 'react-router-dom'
import { deviceAPI, telemetryAPI, eventAPI, commandAPI } from '../services/api'

const { Content } = Layout
const { TabPane } = Tabs

const DeviceDetail = () => {
  const { deviceId } = useParams()
  const navigate = useNavigate()
  const [device, setDevice] = useState(null)
  const [latestTelemetry, setLatestTelemetry] = useState(null)
  const [events, setEvents] = useState([])
  const [commandModalVisible, setCommandModalVisible] = useState(false)
  const [loading, setLoading] = useState(true)
  const [commandForm] = Form.useForm()

  useEffect(() => {
    if (deviceId) {
      fetchDeviceData()
    }
  }, [deviceId])

  const fetchDeviceData = async () => {
    setLoading(true)
    try {
      // 获取设备详情
      const deviceResponse = await deviceAPI.getDevice(deviceId)
      if (deviceResponse.code === 200) {
        setDevice(deviceResponse.data)
        
        // 获取最新遥测数据
        try {
          const telemetryResponse = await telemetryAPI.getLatestTelemetry(deviceId)
          if (telemetryResponse.code === 200) {
            setLatestTelemetry(telemetryResponse.data)
          }
        } catch (error) {
          console.log('获取遥测数据失败:', error)
        }

        // 获取设备事件
        try {
          const eventsResponse = await eventAPI.getDeviceEvents(deviceId, { page_size: 10 })
          if (eventsResponse.code === 200) {
            setEvents(eventsResponse.data?.events || [])
          }
        } catch (error) {
          console.log('获取事件数据失败:', error)
        }
      } else {
        message.error('获取设备详情失败')
        navigate('/devices')
      }
    } catch (error) {
      message.error('获取设备数据失败')
      navigate('/devices')
    } finally {
      setLoading(false)
    }
  }

  const handleSendCommand = async (values) => {
    try {
      const response = await commandAPI.sendCommand(deviceId, values)
      if (response.code === 200) {
        message.success('命令下发成功')
        setCommandModalVisible(false)
        commandForm.resetFields()
      } else {
        message.error(response.message || '命令下发失败')
      }
    } catch (error) {
      message.error('命令下发失败')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'online':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'offline':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
      case 'error':
        return <ExclamationCircleOutlined style={{ color: '#faad14' }} />
      default:
        return <CloseCircleOutlined style={{ color: '#d9d9d9' }} />
    }
  }

  const getStatusTag = (status) => {
    const statusConfig = {
      online: { color: 'success', text: '在线' },
      offline: { color: 'error', text: '离线' },
      error: { color: 'warning', text: '错误' }
    }
    
    const config = statusConfig[status] || { color: 'default', text: status }
    return <Tag color={config.color}>{config.text}</Tag>
  }

  const eventColumns = [
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      render: (time) => new Date(time).toLocaleString()
    },
    {
      title: '事件类型',
      dataIndex: 'event_type',
      key: 'event_type',
      render: (type) => {
        const typeMap = {
          connect: { color: 'success', text: '连接' },
          disconnect: { color: 'error', text: '断开' },
          error: { color: 'warning', text: '错误' },
          command: { color: 'processing', text: '命令' }
        }
        const config = typeMap[type] || { color: 'default', text: type }
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '事件数据',
      dataIndex: 'event_data',
      key: 'event_data',
      render: (data) => data ? JSON.stringify(data) : '-'
    }
  ]

  if (loading) {
    return (
      <Layout>
        <Content style={{ padding: '50px', textAlign: 'center' }}>
          <div>加载中...</div>
        </Content>
      </Layout>
    )
  }

  if (!device) {
    return null
  }

  return (
    <Layout>
      <Content style={{ padding: '24px' }}>
        <Card>
          <div style={{ marginBottom: 16 }}>
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/devices')}
              style={{ marginRight: 16 }}
            >
              返回设备列表
            </Button>
            <Button 
              type="primary" 
              icon={<PlayCircleOutlined />}
              onClick={() => setCommandModalVisible(true)}
            >
              下发命令
            </Button>
          </div>

          <Tabs defaultActiveKey="info">
            <TabPane tab="设备信息" key="info">
              <Row gutter={16}>
                <Col span={16}>
                  <Descriptions 
                    title="设备基本信息" 
                    bordered 
                    column={2}
                  >
                    <Descriptions.Item label="设备名称">{device.name}</Descriptions.Item>
                    <Descriptions.Item label="设备状态">
                      <Space>
                        {getStatusIcon(device.status)}
                        {getStatusTag(device.status)}
                      </Space>
                    </Descriptions.Item>
                    <Descriptions.Item label="设备ID">{device.device_id}</Descriptions.Item>
                    <Descriptions.Item label="设备类型">
                      <Tag color={device.device_type === 'direct' ? 'blue' : 'purple'}>
                        {device.device_type === 'direct' ? '直连设备' : '网关设备'}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="设备描述" span={2}>
                      {device.description || '无描述'}
                    </Descriptions.Item>
                    <Descriptions.Item label="最后在线时间">
                      {device.last_seen ? new Date(device.last_seen).toLocaleString() : '从未在线'}
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间">
                      {new Date(device.created_at).toLocaleString()}
                    </Descriptions.Item>
                  </Descriptions>
                </Col>
                <Col span={8}>
                  <Card title="设备状态统计">
                    <Space direction="vertical" style={{ width: '100%' }} size="large">
                      <Statistic
                        title="设备状态"
                        value={device.status === 'online' ? '在线' : device.status === 'offline' ? '离线' : '异常'}
                        valueStyle={{
                          color: device.status === 'online' ? '#52c41a' : 
                                 device.status === 'offline' ? '#ff4d4f' : '#faad14'
                        }}
                      />
                      <Statistic
                        title="最后在线"
                        value={device.last_seen ? new Date(device.last_seen).toLocaleString() : '从未在线'}
                      />
                    </Space>
                  </Card>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab="实时数据" key="telemetry">
              <Card title="最新遥测数据">
                {latestTelemetry ? (
                  <Descriptions bordered column={3}>
                    {Object.entries(latestTelemetry).map(([key, value]) => (
                      <Descriptions.Item key={key} label={key}>
                        {typeof value === 'number' ? value.toFixed(2) : String(value)}
                      </Descriptions.Item>
                    ))}
                  </Descriptions>
                ) : (
                  <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                    暂无遥测数据
                  </div>
                )}
              </Card>
            </TabPane>

            <TabPane tab="事件记录" key="events">
              <Card title="设备事件记录">
                <Table
                  columns={eventColumns}
                  dataSource={events}
                  rowKey="time"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条记录`,
                  }}
                />
              </Card>
            </TabPane>
          </Tabs>
        </Card>

        {/* 下发命令模态框 */}
        <Modal
          title="下发设备命令"
          open={commandModalVisible}
          onCancel={() => setCommandModalVisible(false)}
          footer={null}
          width={600}
        >
          <Form
            form={commandForm}
            layout="vertical"
            onFinish={handleSendCommand}
          >
            <Form.Item
              name="command"
              label="命令类型"
              rules={[{ required: true, message: '请输入命令类型' }]}
            >
              <Input placeholder="例如: set_config, reboot, update_firmware" />
            </Form.Item>

            <Form.Item
              name="parameters"
              label="命令参数 (JSON格式)"
            >
              <Input.TextArea 
                placeholder='例如: {"sampling_interval": 30, "report_interval": 300}'
                rows={4}
              />
            </Form.Item>

            <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
              <Space>
                <Button onClick={() => setCommandModalVisible(false)}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  下发命令
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Content>
    </Layout>
  )
}

export default DeviceDetail